<template>
  <div class="app-container">
    <div class="depart-container">
      <el-tree
        ref="tree"
        v-model="departId"
        :data="departData"
        node-key="id"
        default-expand-all="true"
        highlight-current="true"
        :props="departTreeProps"
        expand-on-click-node="false"
        @current-change="handleDepartChange"
      />
    </div>
    <div class="content-container">
      <div class="filter-container">
        <el-input v-model="listQuery.key" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleMultiAuthenticate">
          批量授权
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleEnable">
          批量启用
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleDisable">
          批量禁用
        </el-button>
      </div>

      <el-table
        ref="multipleTable"
        :data="tableData"
        border
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="tableSelected"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="fullName"
          label="姓名"
          width="100"
        />
        <el-table-column
          prop="account"
          label="账号"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="departName"
          label="所在部门"
          width="300"
          show-overflow-tooltip
        />
        <el-table-column
          prop="isAdmin"
          width="100"
          label="是否管理员"
        >
          <template slot-scope="scope">
            {{ scope.row.sex===true?"是":"否" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sex"
          width="50"
          label="性别"
        >
          <template slot-scope="scope">
            {{ scope.row.sex===true?"女":"男" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="joinDate"
          label="入职日期"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="leaveDate"
          label="离职日期"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="politicName"
          label="政治面貌"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="email"
          label="邮箱"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="enterpriseEmail"
          label="企业邮箱"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="status"
          width="80"
          label="状态"
        >
          <template slot-scope="scope">
            <font :color="scope.row.status==0?'green':'red'">{{ getUserStatusText(scope.row) }}</font>
          </template>
        </el-table-column>
        <el-table-column
          prop="createDate"
          label="创建时间"
          width="180"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.createDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-dropdown @command="handleMoreCommand">
              <el-button size="mini">
                更多操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown" size="small">
                <el-dropdown-item :command="{method: 'handleView', row: scope.row}">查看</el-dropdown-item>
                <el-dropdown-item :command="{method: 'handleAuthenticate', row: scope.row}">授权</el-dropdown-item>
                <el-dropdown-item :command="{method: 'viewAuthentication', row: scope.row}">查看授权</el-dropdown-item>
                <el-dropdown-item :command="{method: 'resetPassword', row: scope.row}">重置密码</el-dropdown-item>
                <el-dropdown-item :command="{method: 'setLeaved', row: scope.row}">设为离职</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.index" :limit.sync="listQuery.size" @pagination="getList" />

      <el-dialog :disabled="disabled" :title="textMap[dialogStatus]" label-position="right" :visible.sync="dialogFormVisible" width="50">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
          <el-form-item label="部门" prop="pid">
            <el-tree
              ref="tree"
              v-model="temp.pid"
              :data="userDepartData"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :props="departTreeProps"
            />
          </el-form-item>
          <el-form-item label="岗位" prop="postId">
            <el-tree
              ref="treePost"
              v-model="temp.postId"
              :data="userPostData"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :props="departTreeProps"
            />
          </el-form-item>
          <el-form-item v-if="dialogStatus==='update'" label="工号" prop="number">
            <el-input v-model="temp.number" />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="temp.account" />
          </el-form-item>
          <el-form-item label="姓名" prop="fullName">
            <el-input v-model="temp.fullName" />
          </el-form-item>
          <el-form-item label="头像" prop="image">
            <el-upload
              class="avatar-uploader"
              :action="imageAction"
              :headers="userToken"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="temp.image" :src="baseUrl+temp.image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="temp.sex">
              <el-radio :label="false">男</el-radio>
              <el-radio :label="true">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="temp.mobile" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="temp.email" />
          </el-form-item>
          <el-form-item label="企业邮箱" prop="enterpriseEmail">
            <el-input v-model="temp.enterpriseEmail" />
          </el-form-item>
          <el-form-item label="入职日期" prop="joinDate">
            <el-date-picker
              v-model="temp.joinDate"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item v-if="dialogStatus==='update'" label="离职日期" prop="leaveDate">
            <el-date-picker
              v-model="temp.leaveDate"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="政治面貌" prop="political">
            <el-select v-model="temp.political" clearable placeholder="请选择">
              <el-option
                v-for="item in politicalData"
                :key="item.key"
                :label="item.name"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="现住址" prop="familyAddress">
            <el-input v-model="temp.familyAddress" />
          </el-form-item>
          <el-form-item label="家庭住址" prop="originAddress">
            <el-input v-model="temp.originAddress" />
          </el-form-item>
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input v-model="temp.emergencyContact" />
          </el-form-item>
          <el-form-item label="紧急联系人关系" prop="emergencyRelation">
            <el-input v-model="temp.emergencyRelation" />
          </el-form-item>
          <el-form-item label="紧急联系人电话" prop="emergencyMobile">
            <el-input v-model="temp.emergencyMobile" />
          </el-form-item>
          <el-form-item label="在职状态">
            <el-radio-group v-model="temp.leaved">
              <el-radio :label="false">在职</el-radio>
              <el-radio :label="true">离职</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="temp.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">限制登录</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>

      <el-dialog title="授权" :visible.sync="dialogAuthVisible" width="500">
        <Auth :auth-type="2" :object-id="authUserId" :selected-roles="existsUserRoles" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAuthVisible = false">
            取消
          </el-button>
          <el-button type="primary">
            确认
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { page, update, create, setStatus, setUserLeaved, resetPwd } from '@/api/user'
import { getListByUser } from '@/api/role'
import { getByCateCode } from '@/api/dictionary'
import { tree } from '@/api/depart'
import { tree as postTree } from '@/api/post'
import Pagination from '@/components/Pagination'
import Auth from '@/components/Auth'
import waves from '@/directive/waves' // waves directive1
import { getToken } from '@/utils/auth'
import { validMobile, emailValidator } from '@/utils/validate'

var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号码'))
  } else if (!validMobile(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

export default {
  components: { Pagination, Auth },
  directives: { waves },
  data() {
    return {
      listQuery: {
        index: 1,
        size: 15,
        key: '',
        departId: 0
      },
      large: '100',
      baseUrl: process.env.VUE_APP_BASE_API,
      tableData: [],
      treeData: [],
      departData: [],
      postData: [],
      userDepartData: [],
      userPostData: [],
      userToken: { Authorization: '' },
      total: 0,
      pageSize: 15,
      currentPage: 1,
      departTreeProps: { label: 'name' },
      departId: 0,
      dialogFormVisible: false,
      existsUserRoles: [{ name: 'admin', id: 1 }, { name: 'saler', id: 2 }],
      textMap: {
        update: '编辑',
        create: '新建',
        view: '查看'
      },
      temp: {
        id: undefined,
        joinDate: undefined,
        account: '',
        birth: undefined,
        image: '',
        mobile: '',
        political: '',
        fullName: '',
        status: 0,
        sex: false,
        familyAddress: '',
        originAddress: '',
        emergencyContact: '',
        emergencyRelation: '',
        emergencyMobile: '',
        number: '',
        enterpriseEmail: '',
        email: '',
        postIds: [],
        departIds: [],
        leaved: false
      },
      dialogStatus: '',
      tableSelectedKeys: [],
      rules: {
        fullName: [{ required: true, message: '姓名 is required', trigger: 'blur' }],
        account: [{ required: true, message: '账号 is required', trigger: 'blur' }],
        mobile: [{ required: true, trigger: 'blur', validator: validPhone }],
        joinDate: [{ required: true, message: '入职日期 is required', trigger: 'blur' }],
        familyAddress: [{ required: true, message: '现住址 is required', trigger: 'blur' }],
        email: [{ required: true, trigger: 'blur', validator: emailValidator }]
      },
      disabled: false,
      imageAction: '',
      politicalData: {},
      dialogAuthVisible: false,
      authUserId: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  created() {
    this.getList()
    this.getDepartData()
    this.userToken.Authorization = getToken()
    this.imageAction = process.env.VUE_APP_BASE_API + '/user/upload'
    this.getPoliticalData()
    this.getPostData()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.size = this.pageSize
      page(this.listQuery).then(response => {
        this.tableData = response.data.data.records
        this.total = response.data.data.total
        this.currentPage = response.data.data.current

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getDepartData() {
      tree().then(response => {
        this.departData = response.data.data
        this.userDepartData = response.data.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getPostData() {
      postTree().then(response => {
        this.postData = response.data.data
        this.userPostData = response.data.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getPoliticalData() {
      getByCateCode({ categoryCode: 'zzmm' }).then(response => {
        this.politicalData = response.data.data
        // this.userDepartData = response.data.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.getList()
    },
    handleCreate() {
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.resetTemp()
      this.disabled = false
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const model = { user: tempData, posts: this.$refs.treePost.getCheckedKeys(), departs: this.$refs.tree.getCheckedKeys() }
          create(model).then(res => {
            const response = res.data
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const model = { user: tempData, posts: this.$refs.treePost.getCheckedKeys(), departs: this.$refs.tree.getCheckedKeys() }
          update(model).then(res => {
            const response = res.data
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    handleMultiAuthenticate() {

    },
    handleEdit(index, row) {
      this.dialogStatus = 'update'
      this.temp = row
      this.dialogFormVisible = true
      this.disabled = false
      this.$refs.treePost.setCheckedKeys(row.postIds)
      this.$refs.tree.setCheckedKeys(row.departIds)
    },
    handleView(index, row) {
      this.dialogStatus = 'view'
      this.temp = row
      this.dialogFormVisible = true
      this.disabled = true
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        joinDate: undefined,
        account: '',
        birth: undefined,
        image: '',
        mobile: '',
        political: '',
        fullName: '',
        status: 0,
        sex: false,
        familyAddress: '',
        originAddress: '',
        emergencyContact: '',
        emergencyRelation: '',
        emergencyMobile: '',
        number: '',
        enterpriseEmail: '',
        email: '',
        postIds: [],
        departIds: [],
        leaved: false
      }
    },
    handleEnable() {

    },
    handleDisable() {

    },
    tableSelected(selection) {

    },
    handleMoreCommand(command) {
      switch (command.method) {
        case 'resetPassword' :
          this.resetPassword(0, command.row)
          break
        case 'setLeaved' :
          this.setLeaved(0, command.row)
          break
        case 'handleAuthenticate' :
          this.handleAuthenticate(0, command.row)
          break
        case 'viewAuthentication' :
          this.viewAuthentication(0, command.row)
          break
      }
    },
    viewAuthentication(index, row) {

    },
    handleAuthenticate(index, row) {
      this.dialogAuthVisible = true
      this.authUserId = row.id
      this.getUserRoles(row.id)
    },
    resetPassword(index, row) {
      this.$confirm('此操作将把该员工密码重置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd({ id: row.id, password: '123456' }).then(res => {
          const response = res.data
          if (response.success) {
            this.getList()
            this.dialogFormVisible = false
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      })
    },
    setLeaved(index, row) {
      this.$confirm('此操作将把该员工设为离职, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setUserLeaved({ id: row.id, leaved: true }).then(res => {
          const response = res.data
          if (response.success) {
            this.getList()
            this.dialogFormVisible = false
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      })
    },
    handleEditStatus(index, row, status) {

    },
    handleDepartChange(data, node) {
      this.listQuery.departId = data.id
      this.getList()
    },
    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.temp.image = res.data
      } else {
        this.$message({
          message: res.msg,
          type: 'failed'
        })
      }
    },
    handleAvatarError(err, file, fileList) {
      this.$message({
        message: err,
        type: 'failed'
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getUserStatusText(row) {
      if (row.leaved) return '已离职'
      switch (row.status) {
        case 0:
          return '正常'
        case 1:
          return '限制登录'
        case 2:
          return '已删除'
        default:
          return ''
      }
    },
    postTreeCheck(data, checked, node) {
      if (checked) {
        this.$refs.tree1.setCheckedNodes([data])
        this.temp.pid = this.$refs.tree1.getCheckedKeys()
      }
    },
    depTreeCheck(data, checked, node) {
      if (checked) {
        this.$refs.tree1.setCheckedNodes([data])
        this.temp.pid = this.$refs.tree1.getCheckedKeys()[0]
      }
    },
    getUserRoles(userId) {
      var param = { userId: userId }
      getListByUser(param).then(response => {
        this.existsUserRoles = response.data.data

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .depart-container {
    float: left;
    width: 15%;
    border: #ccc solid 1px;
    padding: 5px;
    min-height: 800px;
    overflow: auto;
  }
  .content-container {
    float: left;
    width: 84%;
    margin-left: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
